package com.wunong.smart.address.converter;

import com.wunong.smart.address.client.dto.UserAddressDTO;
import com.wunong.smart.address.client.vo.AddressVO;
import com.wunong.smart.address.client.vo.UserAddressVO;
import com.wunong.smart.address.domain.UserAddressDomain;
import com.wunong.smart.domain.platform.entify.User;
import org.apache.commons.collections.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author create by zealot.zt
 */
public class UserAddressDomainConverter {

    public static UserAddressDomain toDomain(UserAddressVO vo) {
        UserAddressDomain domain = UserAddressDomain.ofInit();

        domain.setId(vo.getId());
        domain.setUser(User.of(vo.getUserId(), vo.getUserRole()));
        domain.setAddressVO(AddressVO.of(vo.getNationCode(), vo.getProvinceCode(),
                vo.getCityCode(), vo.getAreaCode(), vo.getRoadCode(), vo.getAddress()));
        domain.setIsDefault(vo.getIsDefault());
        domain.setMobile(vo.getMobile());
        domain.setName(vo.getName());
        domain.setSex(vo.getSex());
        domain.setDescription(vo.getDescription());

        return domain;
    }

    public static UserAddressDTO toDto(UserAddressDomain domain) {
        UserAddressDTO dto = UserAddressDTO.of();

        dto.init(domain);

        User user = domain.getUser();
        if (Objects.nonNull(user)) {
            dto.setUserId(user.getIdLong());
            dto.setUserRole(user.getRole());
        }
        dto.setAddressVO(domain.getAddressVO());
        dto.setIsDefault(domain.getIsDefault());
        dto.setMobile(domain.getMobile());
        dto.setName(domain.getName());
        dto.setSex(domain.getSex());
        dto.setValid(!domain.isValid());
        dto.setDescription(domain.getDescription());

        return dto;
    }

    public static List<UserAddressDTO> toDto(List<UserAddressDomain> domains) {
        if (CollectionUtils.isEmpty(domains)) {
            return Collections.emptyList();
        }
        return domains.stream().map(UserAddressDomainConverter::toDto)
                .collect(Collectors.toList());
    }

}
